<template>
  <el-dialog
    :title="type === 'edit' ? '编辑用户' : '新增用户'"
    v-model="dialogVisible"
    width="500px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div class="form-wrapper">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            :disabled="type === 'edit'"
            maxlength="20"
            show-word-limit
            @blur="checkUsername"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="type === 'add'">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="formData.nickname"
            placeholder="请输入昵称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleConfirm">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import { addUserApi, checkUserNameApi, updateUserApi } from '@/api/modules/user'
import { UserApi } from '@/api/interface/user'
import { Result } from '@/api/interface'

interface Props {
  visible: boolean
  type: 'add' | 'edit'
  userData?: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  type: 'add',
  userData: () => ({})
})

const emit = defineEmits(['update:visible', 'success', 'cancel'])

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<UserApi.AddUser>({
  uid: '',
  username: '',
  password: '',
  nickname: '',
  role: []
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 监听visible属性变化
watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val
    if (val && props.type === 'edit' && props.userData) {
      // Object.keys(formData).forEach((key) => {
      //   if (props.userData[key] !== undefined) {
      //     formData[key] = props.userData[key]
      //   }
      // })
      Object.assign(formData, val)
      formData.password = ''
      formData.uid = props.userData._id
    }
  }
)

// 监听dialogVisible变化，同步到父组件
watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:visible', val)
  }
)

// 关闭弹窗时重置表单
const handleClosed = () => {
  formRef.value?.resetFields()
  Object.keys(formData).forEach((key) => {
    formData[key] = ''
  })
}

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false
  emit('cancel')
}

const checkUsername = async () => {
  if (!formData.username.trim()) {
    return
  }
  let res = await checkUserNameApi({ params: { username: formData.username } })
  if (res.errCode !== 0) {
    ElMessage.error(res.errMsg)
  }
}

// 确认操作
const handleConfirm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 这里预留API调用位置
        // 根据 props.type 判断是新增还是编辑
        let res: Result
        if (props.type === 'add') {
          // 调用添加用户API
          res = await addUserApi({ params: formData })
        } else {
          // 调用编辑用户API
          res = await updateUserApi({ params: formData })
        }

        // API调用成功
        if (res.errCode === 0) {
          ElMessage.success(props.type === 'add' ? '添加成功' : '修改成功')
          dialogVisible.value = false
          emit('success', formData)
        } else {
          ElMessage.error('添加失败，请联系管理员确认')
        }
      } catch (error) {
        console.error('操作失败', error)
        ElMessage.error('操作失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.form-wrapper {
  padding: 20px;
}
</style>
